package models

import (
	"fmt"
	"github.com/astaxie/beego/orm"
)

type CourseApply struct {
	Id           int
	UserId       int
	StudentId    int
	CourseId     int
	CreateAt     int64
	Status       int
	SupportTimes int
	LeftTimes    int
	Expire       int
}

type CourseApplyQueryParam struct {
	BaseQueryParam
}

type CourseApplyPageEntity struct {
	Id           int
	CourseName   string
	Nickname     string
	Mobile       string
	StudentName  string
	CreateAt     int
	Status       int
	SupportTimes int
	LeftTimes    int
	Expire       int
}

func init() {
	orm.RegisterModel(new(CourseApply))
}

func (this *CourseApply) TableName() string {
	return CourseApplyTBName()
}

func CourseApplyTBName() string {
	return TableName("course_apply")
}

func CourseApplyPageList(params *CourseApplyQueryParam) ([]*CourseApplyPageEntity, int64) {
	query := orm.NewOrm().QueryTable(CourseApplyTBName())
	data := make([]*CourseApplyPageEntity, 0)

	sql := fmt.Sprintf(`SELECT T0.id,T2.nickname,T2.mobile,T3.student_name,T1.course_name,T0.create_at
    FROM %s AS T0
    LEFT JOIN %s AS T1 ON T0.course_id = T1.id
    LEFT JOIN %s AS T2 ON T0.user_id = T2.id
    LEFT JOIN %s AS T3 ON T0.student_id = T2.id
    `, TableName("course_apply"), TableName("course"), TableName("user"), TableName("student"))
	o := orm.NewOrm()

	total, _ := query.Count()
	o.Raw(sql).QueryRows(&data)

	return data, total
}

func CourseApplyOne(Id int) (*CourseApply, error) {
	o := orm.NewOrm()
	m := CourseApply{Id: Id}
	err := o.Read(&m)
	if err != nil {
		return nil, err
	}
	return &m, nil
}
